import { AddOrganizationReq } from '@/api/userCenter/authority/model/organizationModel'
import { addOrg, OrganizationApi } from '@/api/userCenter/authority/organization'
import { useStore } from '@/store'
import { computed, reactive } from '@vue/runtime-core'
import { message } from 'ant-design-vue'
import { AddOrgDialogState } from '../types'

/**
 * 处理新增组织弹框相关逻辑
 * @param searchApi
 * @returns
 */
const useAddOrgDialog = (searchApi: AsyncFun) => {
  const store = useStore()
  const addOrgState = reactive<AddOrgDialogState>({
    visiable: false,
    formData: {
      pid: '',
      name: '',
      code: '',
      level: 0,
    },
  })

  const openAddOrgDialog = (pid: string, level: number) => {
    addOrgState.formData.pid = pid
    addOrgState.formData.level = level
    addOrgState.visiable = true
  }

  const enterAddOrgDialog = async () => {
    const reqData: AddOrganizationReq = {
      pid: addOrgState.formData.pid,
      name: addOrgState.formData.name,
      code: addOrgState.formData.code,
      level: addOrgState.formData.level,
    }
    await addOrg(reqData)
    message.success('添加成功！')
    addOrgState.visiable = false
    await searchApi()
  }
  const addOrgLoading = computed(() =>
    store.getters['global/isOpLoading'](OrganizationApi.ADD_ORGANIZATION)
  )

  return { addOrgState, openAddOrgDialog, enterAddOrgDialog, addOrgLoading }
}

export default useAddOrgDialog
